<?php
/**
 * 上传接口
 */

namespace app\base\controller;
use app\base\library\Uploader;
use think\Exception;
use think\facade\Config;
use think\facade\Request;
use think\Response;

class Uploads extends Common
{


    private $stateMap = array( //上传状态映射表，国际化用户需考虑此处数据的国际化
        "SUCCESS", //上传成功标记，在UEditor中内不可改变，否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上传",
        "没有文件被上传",
        "上传文件为空",
        "ERROR_TMP_FILE" => "临时文件错误",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
        "ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
        "ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
        "ERROR_CREATE_DIR" => "目录创建失败",
        "ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
        "ERROR_FILE_MOVE" => "文件保存时出错",
        "ERROR_FILE_NOT_FOUND" => "找不到上传文件",
        "ERROR_WRITE_CONTENT" => "写入文件内容错误",
        "ERROR_UNKNOWN" => "未知错误",
        "ERROR_DEAD_LINK" => "链接不可用",
        "ERROR_HTTP_LINK" => "链接不是http链接",
        "ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确",
        "INVALID_URL" => "非法 URL",
        "INVALID_IP" => "非法 IP"
    );

    private $CONFIG ;

    public function __construct()
    {
        config('app_trace',false);
        //由于config 获取到的配置文件均被小写 所以采用require 的方式获取配置文件
        //$CONFIG = Config::get('upload.');
        $config_file = __DIR__.'/../../config/upload.php';
        if(file_exists($config_file)){
            $CONFIG = require $config_file;
        }
        $this->CONFIG = $CONFIG;

    }



    /**
     * layui 组件的上传 接口
     */
    public function index(){
        $action = input('post.action');

        try{
            $field_name = key($_FILES);

            if(!count($_FILES)) return ['code' => 0,'msg'=> '无上传文件' ,'data' => ''];

            $error_code = $_FILES[$field_name]['error'];
            $msg = $this->stateMap[$error_code];

            if($msg != 'SUCCESS')return json(['code' => 0,'msg'=> $msg ,'data' => '']);

            switch ($action) {

                /* 上传图片 */
                case 'image':
                    $config = [
                        "pathFormat" => $this->CONFIG['imagePathFormat'],
                        "maxSize" => $this->CONFIG['imageMaxSize'],
                        "allowFiles" => $this->CONFIG['imageAllowFiles']
                    ];
                    break;
                /* 上传视频 */
                case 'video':
                    $config = [
                        "pathFormat" => $this->CONFIG['videoPathFormat'],
                        "maxSize" => $this->CONFIG['videoMaxSize'],
                        "allowFiles" => $this->CONFIG['videoAllowFiles']
                    ];
                    break;
                /* 上传文件 */
                case 'audio':
                    $config = [
                        "pathFormat" => $this->CONFIG['filePathFormat'],
                        "maxSize" => $this->CONFIG['fileMaxSize'],
                        "allowFiles" => $this->CONFIG['fileAllowFiles']
                    ];
                    break;
                /* 上传文件 */
                case 'file':
                    $config = [
                        "pathFormat" => $this->CONFIG['filePathFormat'],
                        "maxSize" => $this->CONFIG['fileMaxSize'],
                        "allowFiles" => $this->CONFIG['fileAllowFiles']
                    ];
                    break;
                default:
                    return ['code' => 0,'msg'=> '找不到请求的方法' ,'data' => ''];
                    break;
            }
            //存储路径改为layuplaod
            $config['pathFormat'] = str_replace('/ueditor/','',$config['pathFormat']);


            $up = new Uploader($field_name, $config);



            $info = $up->getFileInfo();

           if($info['state'] != 'SUCCESS')return json(['code' => 0,'msg'=> $info['state'] ,'data' => '']);


            return json(['code' => 1,'msg'=> '上传成功' ,'data' => $info]);
        }catch (Exception $e){
            return json(['code' => 0,'msg'=> $e->getMessage() ,'data' => '']);
        }

    }

    /**
     * 编辑器的 上传接口
     * @param Request $request
     */
    public function ueditor(Request $request){
        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        header("Content-Type: text/html; charset=utf-8");

        //由于config 获取到的配置文件均被小写 所以采用require 的方式获取配置文件
        //$CONFIG = Config::get('upload.');
        $config_file = __DIR__.'/../../config/upload.php';
        if(file_exists($config_file)){
            $CONFIG = require $config_file;
        }


        $action = input('get.action');



        switch ($action) {
            case 'config':

                exit(json_encode($CONFIG)) ;
                break;

            /* 上传图片 */
            case 'uploadimage':
                $config = array(
                    "pathFormat" => $CONFIG['imagePathFormat'],
                    "maxSize" => $CONFIG['imageMaxSize'],
                    "allowFiles" => $CONFIG['imageAllowFiles']
                );

                $fieldName = $CONFIG['imageFieldName'];

                break;
                /* 上传涂鸦 */
            case 'uploadscrawl':
                //$result = $this->_ueditor_upload();
                break;
            /* 上传视频 */
            case 'uploadvideo':
                $config = array(
                    "pathFormat" => $CONFIG['videoPathFormat'],
                    "maxSize" => $CONFIG['videoMaxSize'],
                    "allowFiles" => $CONFIG['videoAllowFiles']
                );
                $fieldName = $CONFIG['videoFieldName'];
                break;
            /* 上传文件 */
            case 'uploadfile':
                $config = array(
                    "pathFormat" => $CONFIG['filePathFormat'],
                    "maxSize" => $CONFIG['fileMaxSize'],
                    "allowFiles" => $CONFIG['fileAllowFiles']
                );
                $fieldName = $CONFIG['imageFieldName'];
                break;

            /* 列出图片 */
            case 'listimage':
                $result = "";
                break;
            /* 列出文件 */
            case 'listfile':

                break;

            /* 抓取远程文件 */
            case 'catchimage':
                
                break;

            default:
                $result = json_encode(array('state'=> '请求地址出错'));

                break;
        }


        $up = new Uploader($fieldName, $config);

        echo json_encode($up->getFileInfo());

    }

    public function delete_img(){
        $post = input('post.');
        if(file_exists(__ROOT__.$post['path'])){
            @unlink(__ROOT__.$post['path']);
        }
        echo 1;

    }
}